package com.xyy.saas.payment.util;

import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.callback.core.result.CallBackRpcManager;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.common.constants.MqConstant;
import com.xyy.saas.payment.cores.api.BusinessPayResultApi;
import com.xyy.saas.payment.cores.api.CallbackResultApi;
import com.xyy.saas.payment.cores.api.PaymentResultApi;
import com.xyy.saas.payment.cores.constants.CallbackConstants;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.util.mq.MqProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangtianqi
 * @date 2019/10/22 10:26
 */

@Component
public final class CallbackUtil {

    private static Logger LOGGER = LoggerFactory.getLogger(CallbackUtil.class);

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private CallBackRpcManager callBackRpcManager;

    public void sendRPCMsg(String url, ResultVO result, int count) {
        if(!verifyIfCallback(url)) {
            // 无需回调
            LOGGER.info("CallbackUtil#sendRPCMsg url:{} no notify. result:{}", url, JSON.toJSONString(result));
            return ;
        }

        try {
            LOGGER.info("CallbackUtil#sendRPCMsg url:{} result:{}", url, JSON.toJSONString(result));
            PaymentResultApi paymentResultApi = callBackRpcManager.getPaymentResultService(url);
            ResultVO vo = paymentResultApi.callbackOrder(result);

            if(vo == null) {
                LOGGER.error("CallbackUtil#sendRPCMsg error no response url:{} result:{} ", url, JSON.toJSONString(result));
            }
            else {
                if(ResultCodeEnum.SUCCESS.getCode().equals(vo.getCode())) {
                    LOGGER.info("CallbackUtil#sendRPCMsg success url:{} result:{}", url, JSON.toJSONString(result));
                    return;
                }
                else {
                    LOGGER.warn("CallbackUtil#sendRPCMsg error wrong response url:{} result:{} resultVO:{}", url, JSON.toJSONString(result), JSON.toJSONString(vo));
                }
            }
        }
        catch(Exception e) {
            LOGGER.error("CallbackUtil#sendRPCMsg  error", e);
        }

        int countMax = MqConstant.DELAY_LEVELS.length - 1;

        if(count <= countMax) {
            // 处理重传机制
            Map<String, String> mqMsg = new HashMap<>(4);
            mqMsg.put("callBack", url);
            mqMsg.put("count", String.valueOf(count));
            mqMsg.put("msg", JSON.toJSONString(result));
            mqProducer.syncSendDelayMsg(RocketMqTopic.TOPIC_RETRY_NOTIFY, JSON.toJSONString(mqMsg), MqConstant.DELAY_LEVELS[count]);
            LOGGER.info("CallbackUtil#checkRPCMsg callback resend url:{} result:{}, count:{}", url, JSON.toJSONString(result), count);
        }
        else {
            //重试达到上限 记录日志
            LOGGER.error("CallbackUtil#checkRPCMsg call back count max error, url:{} count:{} result:{}", url, count, JSON.toJSONString(result));
        }
    }

    public void sendResultMsg(String url, ResultVO result, int count) {
        if(!verifyIfCallback(url)) {
            // 无需回调
            LOGGER.info("CallbackUtil#sendResultMsg url:{} no notify. result:{}", url, JSON.toJSONString(result));
            return ;
        }

        try {
            LOGGER.info("CallbackUtil#sendResultMsg url:{} result:{}", url, JSON.toJSONString(result));
            CallbackResultApi callbackResultApi = callBackRpcManager.getCallbackResultService(url);
            ResultVO vo = callbackResultApi.callbackResult(result);

            if(vo == null) {
                LOGGER.error("CallbackUtil#sendResultMsg error no response url:{} result:{} ", url, JSON.toJSONString(result));
            }
            else {
                if(ResultCodeEnum.SUCCESS.getCode().equals(vo.getCode())) {
                    LOGGER.info("CallbackUtil#sendResultMsg success url:{} result:{}", url, JSON.toJSONString(result));
                    return;
                }
                else {
                    LOGGER.warn("CallbackUtil#sendResultMsg error wrong response url:{} result:{} resultVO:{}", url, JSON.toJSONString(result), JSON.toJSONString(vo));
                }
            }
        }
        catch(Exception e) {
            LOGGER.error("CallbackUtil#sendResultMsg  error", e);
        }

        int countMax = MqConstant.DELAY_LEVELS.length - 1;

        if(count <= countMax) {
            // 处理重传机制
            Map<String, String> mqMsg = new HashMap<>(4);
            mqMsg.put("callBack", url);
            mqMsg.put("count", String.valueOf(count));
            mqMsg.put("msg", JSON.toJSONString(result));
            mqProducer.syncSendDelayMsg(RocketMqTopic.TOPIC_CALLBACK_RETRY_NOTIFY, JSON.toJSONString(mqMsg), MqConstant.DELAY_LEVELS[count]);
            LOGGER.info("CallbackUtil#sendResultMsg callback resend url:{} result:{}, count:{}", url, JSON.toJSONString(result), count);
        }
        else {
            //重试达到上限 记录日志
            LOGGER.error("CallbackUtil#sendResultMsg call back count max error, url:{} count:{} result:{}", url, count, JSON.toJSONString(result));
        }
    }

    public void sendBusinessPayMsg(String url, ResultVO result, int count) {
        if(!verifyIfCallback(url)) {
            // 无需回调
            LOGGER.info("CallbackUtil#sendBusinessPayMsg url:{} no notify. result:{}", url, JSON.toJSONString(result));
            return ;
        }

        try {
            LOGGER.info("CallbackUtil#sendBusinessPayMsg url:{} result:{}", url, JSON.toJSONString(result));
            BusinessPayResultApi businessPayResultApi = callBackRpcManager.getBusinessPayResultService(url);
            ResultVO vo = businessPayResultApi.callbackBusinessPay(result);

            if(vo == null) {
                LOGGER.error("CallbackUtil#sendBusinessPayMsg error no response url:{} result:{} ", url, JSON.toJSONString(result));
            }
            else {
                if(ResultCodeEnum.SUCCESS.getCode().equals(vo.getCode())) {
                    LOGGER.info("CallbackUtil#sendBusinessPayMsg success url:{} result:{}", url, JSON.toJSONString(result));
                    return;
                }
                else {
                    LOGGER.warn("CallbackUtil#sendBusinessPayMsg error wrong response url:{} result:{} resultVO:{}", url, JSON.toJSONString(result), JSON.toJSONString(vo));
                }
            }
        }
        catch(Exception e) {
            LOGGER.error("CallbackUtil#sendBusinessPayMsg  error", e);
        }

        int countMax = MqConstant.DELAY_LEVELS.length - 1;

        if(count <= countMax) {
            // 处理重传机制
            Map<String, String> mqMsg = new HashMap<>(4);
            mqMsg.put("callBack", url);
            mqMsg.put("count", String.valueOf(count));
            mqMsg.put("msg", JSON.toJSONString(result));
            mqProducer.syncSendDelayMsg(RocketMqTopic.TOPIC_RETRY_NOTIFY_BUSINESS_PAY, JSON.toJSONString(mqMsg), MqConstant.DELAY_LEVELS[count]);
            LOGGER.info("CallbackUtil#sendBusinessPayMsg callback resend url:{} result:{}, count:{}", url, JSON.toJSONString(result), count);
        }
        else {
            //重试达到上限 记录日志
            LOGGER.error("CallbackUtil#sendBusinessPayMsg call back count max error, url:{} count:{} result:{}", url, count, JSON.toJSONString(result));
        }
    }

    /**
     * 校验是否回调，true 需要回调  false 无需回调
     * @param callback
     * @return
     */
    private boolean verifyIfCallback(String callback) {
        if(CallbackConstants.NO_NOTIFY.equals(callback)) {
            return false;
        }

        return true;
    }
}
